import React from "react";
import Plus from "../icons/Plus";
import colors from "../assets/colors.json";
import { getRandomNumber } from "../utils";
import { useRef, useContext } from "react";
import { addNote } from "../request/api";
import { NoteContext } from "../context";

const AddButton = () => {
  const posRef = useRef(10);
  const { setNotes } = useContext(NoteContext);
  const handleClick = async () => {
    const i = getRandomNumber(0, colors.length - 1);

    const payload = {
      colors: colors[i],
      position: {
        x: posRef.current,
        y: posRef.current,
      },
    };

    const { data: newNote } = await addNote(payload);
    posRef.current += 20;
    setNotes((preNotes) => [newNote, ...preNotes]);
  };
  return (
    <div id="add-btn" onClick={handleClick}>
      <Plus />
    </div>
  );
};
export default AddButton;
